import { reactive, ref } from 'vue';

interface Options<T = any> {
  // api
  apiFn: (params: any) => Promise<{ data: T }>;
  // api请求参数
  params?: any;
  // api返回值不是约定的TableResponse的处理
  callback?: (data: T) => T;
  // 显示分页数据
  isPageable?: boolean;
  // 立即执行getList函数
  immediate?: boolean;
}

export const useTable = (options: Options) => {
  const tableData = ref<any>([]);
  const loading = ref<boolean>(false);
  // eslint-disable-next-line unicorn/prefer-structured-clone
  const paramsInit = JSON.parse(JSON.stringify(options.params || {}));
  const page = reactive({
    page: 1,
    pageSize: 10,
    pageSizes: ['10', '20', '30', '50'],
    total: 10,
  });
  const summing = ref<any>(0);
  const getList = async () => {
    loading.value = true;
    const isPageable: boolean = options.isPageable ?? true;
    const pageParams = isPageable
      ? { pageNum: page.page, pageSize: page.pageSize }
      : {};
    const totalParams = Object.assign({}, options.params, pageParams);
    let data: any = await options
      .apiFn(totalParams)
      .finally(() => (loading.value = false));
    // console.log('1212', data);
    options.callback && (data = options.callback(data));
    const date = isPageable ? data.rows : data;
    tableData.value = date;
    page.total = data.total;
    summing.value = data.summing || {};
  };

  const handleSizeChange = async (val: number) => {
    page.page = 1;
    page.pageSize = val;
    await getList();
  };

  const handleCurrentChange = async (val: number) => {
    page.page = val;
    await getList();
  };

  const resetParams = () => {
    for (const key in paramsInit) {
      paramsInit[key] = '';
    }
    Object.keys(paramsInit).forEach((item) => {
      // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
      options.params![item] = paramsInit[item];
    });
    getList();
  };

  if (options.immediate ?? true) getList();

  return {
    tableData,
    page,
    loading,
    summing,
    getList,
    resetParams,
    handleSizeChange,
    handleCurrentChange,
  };
};
